<template>
    <div class="pool-list">
        <div class="move-box">
            <RiskLeftModule
                v-model="inputValueLeft"
                @on-submit="submitInput"
                @on-handleNode="clickNode"
                :placeholders="ltitleName"
                :treeData="treeData"
                :leftHeight="leftHgt"
                :currentKey="'1'"
                ref="leftTree"
                :defaultExpandedKeys="defaultExpandedKeys"
            >
                <template slot="ltitle">公司池设置</template>
            </RiskLeftModule>

            <!-- 公司池信息 -->
            <template v-if="cutInfo === '本地' || cutInfo === '外部'">
                <RiskRightModule v-model="inputValueRight" :rightPlace="rtitleName" :rightHeight="leftHgt" @on-keyup="selectGroup">
                    <p slot="rtitle">公司池信息</p>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" @click="selectGroup">查询</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0113" v-show="cutInfo === '本地'" @click="addGroup">新增</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0144" @click="downLoadGroupFile">导出</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="danger" size="mini" v-authCode.show="B_0114" v-show="cutInfo === '本地'" @click="deleteGroup"
                            >删除</el-button
                        >
                    </span>
                    <slot>
                        <el-table
                            :data="tableData"
                            border
                            size="mini"
                            style="width: 100%"
                            height="79vh"
                            @selection-change="handleSelectionChange"
                            @sort-change="handleSort"
                        >
                            <!-- <el-table-column
                            type="selection"
                            :filters="[{ text: '选择当前页', value: '家' }]"
                            :filter-multiple="false"
                            :filter-method="filterHandler"
                            width="55"
                            size="mini"
                        > -->
                            <el-table-column type="selection" width="55" size="mini"> </el-table-column>
                            <el-table-column prop="isGrCode" label="公司池编号"> </el-table-column>
                            <el-table-column prop="isGrName" label="公司池名称" show-overflow-tooltip :formatter="formatter"> </el-table-column>
                            <el-table-column prop="issueGroupType" label="公司池类型" show-overflow-tooltip>
                                <template #default="{ row }"> {{ Dict.statusOptions[row.issueGroupType] }}</template>
                            </el-table-column>
                            <el-table-column prop="issueGroupMain" label="关联方" :formatter="formatter"> </el-table-column>
                            <el-table-column prop="sourceType" label="数据来源" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    <span>{{ Dict.SourceType[scope.row.sourceType] }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="dtCtDate" label="创建日期" show-overflow-tooltip sortable width="180">
                                <template slot-scope="scope">
                                    <span>{{ dateFormat(scope.row.dtCtDate) }} {{ timeFormat(scope.row.dtCtTime) }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="dtCtUser" label="创建者" show-overflow-tooltip v-if="showParamByDocking()"> </el-table-column>
                            <el-table-column label="操作" width="120">
                                <template slot-scope="scope">
                                    <RiskIconButton
                                        type="primary"
                                        icon="el-icon-edit"
                                        v-authCode="B_0115"
                                        topTitle="编辑公司池"
                                        :disabled="cutInfo === '外部'"
                                        @on-click="editGroupRow(scope.row)"
                                    ></RiskIconButton>
                                    <RiskIconButton
                                        type="danger"
                                        icon="el-icon-delete"
                                        v-authCode="B_0114"
                                        topTitle="删除公司池"
                                        :disabled="cutInfo === '外部'"
                                        @on-click="deleteGroupRow(scope.row)"
                                    ></RiskIconButton>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="block">
                            <risk-pagination :paging="groupPage" @page-change="groupPageChange"></risk-pagination>
                        </div>
                    </slot>
                </RiskRightModule>
                <!-- 新增 -->
                <yh-dialog :title="groupDialog.title" :visible.sync="groupDialog.visible" width="400px" drag>
                    <el-form label-width="140px" size="mini">
                        <el-form-item label="公司池编号">
                            <el-input placeholder="自动生成" style="width: 220px" disabled v-model="groupData.isGrCode"></el-input>
                        </el-form-item>
                        <el-form-item label="公司池名称">
                            <el-input style="width: 220px" v-model.trim="groupData.isGrName" @change="onSetIsGroup($event, 'isGrName')"></el-input>
                        </el-form-item>
                        <el-form-item label="公司池类型">
                            <el-select v-model="groupData.issueGroupType" placeholder="请选择公司池类型" filterable>
                                <el-option v-for="(value, key) in statusOptions" :key="key" :label="key + ' ' + value" :value="key"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="关联方">
                            <el-input
                                style="width: 220px"
                                v-model.trim="groupData.issueGroupMain"
                                @change="onSetIsGroup($event, 'issueGroupMain')"
                            ></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button size="mini" @click="groupDialogClosed"> 取 消 </el-button>
                        <el-button size="mini" type="primary" @click="groupDialogConfirm"> 确 定 </el-button>
                    </div>
                </yh-dialog>
            </template>

            <!-- 公司池明细 -->
            <template v-else>
                <RiskRightModule v-model="inputDetailValueRight" :rightPlace="right2Place" :rightHeight="leftHgt">
                    <p slot="rtitle">公司池明细信息</p>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" @click="selectDetail">查询</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button
                            type="primary"
                            size="mini"
                            v-authCode.show="B_0116"
                            v-show="this.currentData.sourceType === '1'"
                            @click="editDetail"
                            >编辑</el-button
                        >
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0145" @click="loadoutDetail">导出明细</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0147" @click="loadinDetail">导入明细</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button
                            type="danger"
                            size="mini"
                            v-authCode.show="B_0117"
                            v-show="this.currentData.sourceType === '1'"
                            @click="deleteDetail"
                            >删除</el-button
                        >
                    </span>
                    <slot>
                        <el-table
                            :key="tableDataKey"
                            :data="tableData"
                            border
                            size="mini"
                            style="width: 100%"
                            height="79vh"
                            @selection-change="handleSelectionDetailChange"
                        >
                            <!-- v-tableTop="currentPage" -->
                            <!-- <el-table-column
                            type="selection"
                            :filters="[{ text: '选择当前页', name: '家' }]"
                            :filter-multiple="false"
                            :filter-method="filterHandler"
                            width="55"
                            size="mini"
                        >
                        </el-table-column> -->
                            <el-table-column type="selection" width="55" size="mini"> </el-table-column>
                            <el-table-column prop="issueCode" label="公司编号"> </el-table-column>
                            <el-table-column prop="issueName" label="公司名称" show-overflow-tooltip :formatter="formatter"> </el-table-column>
                            <el-table-column prop="issueNameSt" label="公司简称" show-overflow-tooltip :formatter="formatter"> </el-table-column>
                            <el-table-column prop="dtMdDate" label="添加日期" show-overflow-tooltip width="180" sortable>
                                <template slot-scope="scope">
                                    <span>{{ dateFormat(scope.row.dtMdDate) }} {{ timeFormat(scope.row.dtMdTime) }}</span>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column prop="dtMdDate" label="添加日期" :formatter="formatterDate"></el-table-column> -->
                            <!-- <el-table-column prop="dtMdTime" label="添加时间" :formatter="formatterTime"> </el-table-column> -->
                            <el-table-column prop="dtMdUser" label="添加者" v-if="showParamByDocking()"> </el-table-column>
                        </el-table>
                        <div class="block">
                            <el-pagination
                                background
                                @current-change="detailPageChange"
                                layout="total, prev, pager, next"
                                :total="detailPage.total"
                                :page-size="detailPage.pageSize"
                                :current-page.sync="detailPage.currentPage"
                                v-show="tableData.length > 0"
                            >
                            </el-pagination>
                        </div>
                    </slot>
                </RiskRightModule>
                <!-- 明细编辑 -->
                <div>
                    <yh-dialog
                        :title="editDetailDialog.title"
                        :visible.sync="editDetailDialog.visible"
                        width="900px"
                        class="editDialog"
                        drag
                        append-to-body
                        :fullscreen="fullscreenIs"
                        :class="fullscreenIs == true ? 'testHeight' : ''"
                        :before-close="handleClose"
                    >
                        <i :class="fullscreenIs == false ? 'el-icon-full-screen' : 'el-icon-crop'" @click="changeScreen"></i>
                        <RiskTrantableCompanyPool
                            ref="tranTable"
                            sort="issueName"
                            indexKey="issueCode"
                            leftPlaceholder="编号/名称"
                            rightPlaceholder="编号/名称"
                            :columns="tranColumns"
                            :rightTableData="rightTranData"
                            :grCode="currentData.id"
                            :searchNames="['issueCode', 'issueName']"
                            url="/componyPool/issueGroup/allIssue"
                            url2="/componyPool/issueGroup/insert/isGroup/issue/"
                            :idName="['issueCode']"
                            v-if="editDetailDialog.visible"
                            style="min-height: 430px"
                            :fullscreenIs="fullscreenIs"
                        />
                        <div slot="footer" class="dialog-footer">
                            <el-button size="mini" @click="editDetailDialogClosed(true)"> 取 消 </el-button>
                            <el-button size="mini" type="primary" @click="editDetailDialogConfirm">确 定 </el-button>
                        </div>
                    </yh-dialog>
                </div>
            </template>
            <!-- 删除 -->
            <div>
                <yh-dialog :title="deleteDialog.title" :visible.sync="deleteDialog.visible" width="500px" drag>
                    <div class="remove-text">
                        <!-- <span v-for="(itme, index) in delPendingData" :key="index"> {{ itme }} , </span> -->
                        <p>{{ delPendingData.join(',') }}</p>
                    </div>
                    <div slot="footer" class="dialog-footer">
                        <el-button size="mini" @click="deleteDialogClosed"> 取 消 </el-button>
                        <el-button size="mini" type="primary" @click="deleteDialogConfirm">确 定 </el-button>
                    </div>
                </yh-dialog>
            </div>
            <!-- 导入公司池明细 -->
            <div>
                <yh-dialog :title="loadinDetailDialog.title" :visible.sync="loadinDetailDialog.visible" width="650px" drag>
                    <div>
                        <el-button @click="putDictfile" type="primary" style="margin-bottom: 5px">选择文件</el-button><i> {{ fileNames }} </i>
                        <input type="file" ref="putInput" style="display: none" @change="putDictfiles" />
                        <el-button v-if="putTableDataList.length" @click="downLoadFail" type="primary" style="margin-bottom: 5px; float: right">
                            导出失败明细
                        </el-button>
                        <el-table :data="putTableData" style="width: 100%" border size="mini" height="300px">
                            <el-table-column label="公司编号" prop="issueCode"></el-table-column>
                            <el-table-column label="公司名称" prop="issueName" show-overflow-tooltip></el-table-column>
                            <el-table-column label="公司简称" prop="issueNameSt"></el-table-column>
                            <el-table-column label="失败原因" prop="errorMsg"></el-table-column>
                        </el-table>
                        <div class="block">
                            <el-pagination
                                background
                                @current-change="loadPageChange"
                                layout="total, prev, pager, next"
                                :total="loadPage.total"
                                :page-size="loadPage.pageSize"
                                :current-page.sync="loadPage.currentPage"
                                v-show="putTableDataList.length > 0"
                            >
                            </el-pagination>
                        </div>
                        <span style="color: red">备注：导入格式请参考公司池明细导出的结果</span>
                    </div>
                    <div slot="footer" class="dialog-footer">
                        <el-button size="mini" @click="loadinDetailDialogClosed"> 取 消 </el-button>
                        <el-button size="mini" type="primary" @click="loadinDetailDialogConfirm">确 定 </el-button>
                    </div>
                </yh-dialog>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

import RiskLeftModule from '@/common/components/risk-left-module.vue';
import RiskRightModule from '@/common/components/risk-right-module.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import {
    dateFormat,
    formatter,
    formatterDate,
    formatterNumber,
    formatterTime,
    getCurrentPageData,
    showParamByDocking,
    timeFormat,
} from '@/utils/tools';
import XEUtils from 'xe-utils';
import { DialogVO } from '@yhfin/biz';
import Dict from './dict/index';
import { downLoadFile } from '@/utils/request';
import * as XLSX from 'xlsx';
import RiskTrantableCompanyPool from '@/common/components/risk-trantable-company-pool.vue';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'CompanyPool',
    components: {
        RiskLeftModule,
        RiskRightModule,
        RiskIconButton,
        RiskTrantableCompanyPool,
        RiskPagination,
    },
})
export default class CompanyPool extends Vue {
    formatterDate = formatterDate;
    formatterTime = formatterTime;
    formatter = formatter;
    dateFormat = dateFormat;
    timeFormat = timeFormat;
    formatterNumber = formatterNumber;
    showParamByDocking = showParamByDocking;
    private inputValueLeft: string = '';
    private ltitleName: string = '编号/名称';
    private leftHgt: string = '100vh';
    private inputValueRight: string = '';
    private inputDetailValueRight: string = '';

    private rtitleName: string = '公司池编码/名称';
    private right2Place: string = '公司编号/名称';
    private localList: any[] = [];
    private outsideList: any[] = [];
    private groupDialog: DialogVO = new DialogVO();
    private deleteDialog: DialogVO = new DialogVO();
    private editDetailDialog: DialogVO = new DialogVO();
    private loadinDetailDialog: DialogVO = new DialogVO();
    private putTableData: any[] = []; // 上传的数据
    private putTableDataList: any[] = [];
    private defaultExpandedKeys: any[] = ['1'];
    private fileNames: string = ''; // 上传文件名
    private tranColumns: any[] = [
        {
            label: '编号',
            prop: 'issueCode',
            width: 80,
        },
        {
            label: '名称',
            prop: 'issueName',
            width: 165,
        },
    ];
    private rightTranData: any[] = []; // 穿梭框右侧数据

    private groupDataBackup: any = {};
    private groupData: any = {
        isGrCode: '自动生成',
        isGrName: '',
        issueGroupMain: '',
        issueGroupType: '0',
    };
    private groupPage: pages = {
        currentPage: 1,
        pageSize: 50,
    };

    private detailPage: pages = {
        currentPage: 1,
        pageSize: 50,
    };

    private loadPage: pages = {
        currentPage: 1,
        pageSize: 50,
    };

    private treeData: any[] = [
        {
            id: '1',
            label: '本地',
            children: [],
        },
        // {
        //     id: '0',
        //     label: '外部',
        //     children: [],
        // },
    ];
    private cutInfo: string = '本地';

    loading: boolean = false;

    private currentData: any = {};

    private tableData: any[] = []; // 显示数据
    private tableDataKey = 0;

    private tableDataList: any[] = []; // 表格所有数据

    private tableDataSearched: any[] = []; // 搜索表格数据

    private hasSelectedData: any[] = []; // 已勾选数据

    private delPendingData: any[] = []; // 待删除数据

    Dict: any = new Dict();

    private fullscreenIs: boolean = false;

    private statusOptions = this.Dict.statusOptions;

    mounted() {
        this.groupDataBackup = JSON.parse(JSON.stringify(this.groupData));
        this.getCompanyInfo();
    }

    // 改变窗口大小
    private changeScreen(): void {
        this.fullscreenIs = !this.fullscreenIs;
    }

    // 分组分页切换
    private groupPageChange(val: number): void {
        if (this.inputValueRight) {
            this.groupPage.total = this.tableDataSearched.length;
            if (val !== undefined) {
                this.groupPage.currentPage = val;
            }
            this.tableData = getCurrentPageData(this.tableDataSearched, this.groupPage.currentPage, this.groupPage.pageSize);
        } else {
            this.groupPage.total = this.tableDataList.length;
            if (val !== undefined) {
                this.groupPage.currentPage = val;
            }
            this.tableData = getCurrentPageData(this.tableDataList, this.groupPage.currentPage, this.groupPage.pageSize);
        }
    }

    // 明细分页
    private detailPageChange(val: number): void {
        this.tableDataKey++;
        if (this.inputDetailValueRight) {
            this.detailPage.total = this.tableDataSearched.length;
            this.detailPage.currentPage = val;
            this.tableData = getCurrentPageData(this.tableDataSearched, this.detailPage.currentPage, this.detailPage.pageSize);
        } else {
            this.detailPage.total = this.tableDataList.length;
            this.detailPage.currentPage = val;
            this.tableData = getCurrentPageData(this.tableDataList, this.detailPage.currentPage, this.detailPage.pageSize);
        }
    }

    // 导入数据分页
    private loadPageChange(val: number): void {
        this.loadPage.total = this.putTableDataList.length;
        this.loadPage.currentPage = val;
        this.putTableData = getCurrentPageData(this.putTableDataList, this.loadPage.currentPage, this.loadPage.pageSize);
    }

    //   公司池信息
    private getCompanyInfo(): void {
        this.$axios.get('/componyPool/issueGroup/all').then((res: any) => {
            let local = [];
            let outside = [];
            this.localList = [];
            this.outsideList = [];
            for (let item of res) {
                if (item.sourceType === '1') {
                    local.push(item);
                    let datas = item.isGrCode + '-' + item.isGrName;
                    this.localList.push(Object.assign({ label: datas, id: item.isGrCode }, item));
                } else {
                    outside.push(item);
                    let datas = item.isGrCode + '-' + item.isGrName;
                    this.outsideList.push(Object.assign({ label: datas, id: item.isGrCode }, item));
                }
            }
            this.treeData[0].children = this.localList;

            this.tableDataList = this.cutInfo == '外部' ? this.outsideList : this.localList;
            this.selectGroup();
        });
    }

    // 分页处理
    private getPageInfo(): void {
        this.groupPage.total = this.tableDataList.length;
        this.tableData = getCurrentPageData(this.tableDataList, this.groupPage.currentPage, this.groupPage.pageSize);
    }

    // 节点点击
    private clickNode(data: any): void {
        this.currentData = data;
        this.cutInfo = data.label;
        if (this.cutInfo === '本地' || this.cutInfo === '外部') {
            this.getGroupInfo();
        } else {
            this.getDetailInfo(data.id);
        }
    }

    // 获取公司池数据
    private getGroupInfo(): void {
        this.loading = true;
        if (this.cutInfo === '本地') {
            this.tableDataList = this.localList;
        } else {
            this.tableDataList = this.outsideList;
        }
        this.selectGroup();
        this.loading = false;
    }

    // 获取公司池明细数据
    private getDetailInfo(id: string): void {
        this.loading = true;
        this.$axios
            .get('/componyPool/issueGroup/issueList/' + this.currentData.id)
            .then((res: any) => {
                this.tableDataList = res;
                this.selectDetail();
                this.loading = false;
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 公司池查询
    private selectGroup(): void {
        this.tableDataSearched = this.handleFilter(this.tableDataList, this.inputValueRight, 'isGrCode', 'isGrName');
        this.groupPageChange(1);
    }

    // 公司池|| 明细筛选数据
    private handleFilter(dataSource: any, param: any, code: string, name: string): any {
        if (!param || !dataSource) {
            return dataSource;
        } else {
            return dataSource.filter(
                (item: any) =>
                    (item[name] || '').toUpperCase().includes(param.toUpperCase()) || (item[code] || '').toUpperCase().includes(param.toUpperCase())
            );
        }
    }

    // 公司池新增
    private addGroup(): void {
        this.groupData = JSON.parse(JSON.stringify(this.groupDataBackup));
        this.groupDialog = this.groupDialog.getAddDialog('新增公司池');
    }

    private onSetIsGroup(value: string, field: string) {
        if (value != '' || value != null) {
            value = value.trim();
            if (field == 'isGrName' && value.length > 30) {
                this.yh_message_error('公司池名称超出字符长度限制!');
            } else if (field == 'issueGroupMain' && value.length > 6) {
                this.yh_message_error('关联方名称长度超过字符长度限制!');
            }
        }
        return value;
    }
    // 确认添加公司池
    private groupDialogConfirm(): void {
        if (!this.groupData.isGrName) {
            this.yh_message_error('公司池名称不能为空!');
            return;
        } else {
            console.log(this.groupData.isGrName.length);
            if (this.groupData.isGrName.length > 30) {
                this.yh_message_error('公司池名称超出字符长度限制！');
                return;
            }
        }
        if (this.groupData.issueGroupMain && this.groupData.issueGroupMain.length > 6) {
            this.yh_message_error('关联方长度超过字符长度限制！');
            return;
        }

        if (this.groupDialog.action === 1) {
            this.$axios.post('/componyPool/issueGroup/insert/isGroup', this.groupData).then(res => {
                this.yh_message_success('新增成功');
                this.getCompanyInfo();
                this.groupDialogClosed();
            });
        } else {
            this.$axios.put('/componyPool/issueGroup/update', this.groupData).then(res => {
                this.yh_message_success('编辑成功');
                this.getCompanyInfo();
                this.groupDialogClosed();
            });
        }
    }

    private groupDialogClosed(): void {
        this.groupDialog.visible = false;
    }

    // 公司池导出
    private downLoadGroupFile(): void {
        // let type = this.cutInfo == '本地' ? '1' : '2';
        let type = '0';
        let data = this.hasSelectedData;
        if (this.hasSelectedData.length < 1 || !this.hasSelectedData) {
            data = XEUtils.map(this.tableDataList, item => item.isGrCode);
        }
        downLoadFile({
            url: '/componyPool/export/company/pool/1/' + type,
            method: 'post',
            data: data,
        });
    }

    // 公司池导出
    private deleteGroup(): void {
        if (this.hasSelectedData.length < 1) {
            this.yh_message_warn('未选择删除项');
        } else {
            this.delPendingData = this.hasSelectedData;
            this.deleteDialog = this.deleteDialog.getDeleteDialog('确定删除公司池？');
        }
    }

    private deleteDialogClosed(): void {
        this.deleteDialog.visible = false;
    }

    // 确认删除
    private deleteDialogConfirm(): void {
        if (this.cutInfo === '本地' || this.cutInfo === '外部') {
            this.$axios({
                url: '/componyPool/issueGroup/delete',
                method: 'DELETE',
                data: this.delPendingData,
            }).then(res => {
                this.yh_message_success('删除成功');
                this.getCompanyInfo();
                this.deleteDialogClosed();
            });
        } else {
            this.$axios({
                url: '/componyPool/issueGroup/delete/issue/' + this.currentData.id,
                method: 'DELETE',
                data: this.delPendingData,
            }).then(res => {
                this.yh_message_success('删除成功');
                this.getDetailInfo(this.currentData.id);
                this.deleteDialogClosed();
            });
        }
        this.hasSelectedData = [];
    }

    // 左侧搜索
    private submitInput(): void {}

    // 勾选
    private handleSelectionChange(data: any[]): void {
        this.hasSelectedData = XEUtils.map(data, item => item.isGrCode);
    }

    private handleSelectionDetailChange(data: any[]): void {
        this.hasSelectedData = XEUtils.map(data, item => item.issueCode);
    }

    // 表格编辑公司池
    private editGroupRow(row): void {
        this.groupDialog = this.groupDialog.getUpdateDialog('编辑公司池');
        this.groupData = JSON.parse(JSON.stringify(row));
    }

    // 表格删除公司池
    private deleteGroupRow(row: any): void {
        this.delPendingData = [row.id];
        this.deleteDialog = this.deleteDialog.getDeleteDialog('确定删除公司池？');
    }

    // 明细查询
    private selectDetail(): void {
        this.tableDataSearched = this.handleFilter(this.tableDataList, this.inputDetailValueRight, 'issueCode', 'issueName');
        this.detailPageChange(1);
    }

    // 明细编辑
    private editDetail(): void {
        this.editDetailDialog = this.editDetailDialog.getAddDialog('编辑公司池');
        this.rightTranData = this.tableDataList;
    }

    // 明细编辑'确认'
    private editDetailDialogConfirm(needNotify = true): any {
        let needData = [];
        if (needNotify) {
            this.yh_message_success('编辑成功');
            this.getDetailInfo(this.currentData.id);
            this.editDetailDialogClosed();
        } else {
            const changed = (this.$refs.tranTable as any).getChanged();
            if (changed) {
                // 取消更新的副本，复原数据，只需要更新数据，不用提示
                needData = this.tableDataList.map(item => item.issueCode);
                needData = [...new Set(needData)];
                return new Promise((resolve, reject) => {
                    this.$axios.post('/componyPool/issueGroup/insert/isGroup/issue/' + this.currentData.id, needData).then((res: any) => {
                        resolve(res);
                    });
                });
            } else {
            }
        }
    }

    async editDetailDialogClosed(needRestore = false) {
        if (needRestore) {
            await this.editDetailDialogConfirm(false);
            await (this.editDetailDialog.visible = false);
        } else {
            this.editDetailDialog.visible = false;
        }
    }

    //  导出明细
    private loadoutDetail(): void {
        let data = this.hasSelectedData;
        if (this.hasSelectedData.length < 1 || !this.hasSelectedData) {
            data = XEUtils.map(this.hasSelectedData, item => item.issueCode);
        }
        downLoadFile({
            url: '/componyPool/export/company/' + this.currentData.id,
            method: 'post',
            data: data,
        });
    }

    // 导入明细
    private loadinDetail(): void {
        this.loadinDetailDialog = this.loadinDetailDialog.getAddDialog('导入公司池明细' + '(' + this.currentData.id + ')');
        this.putTableDataList = [];
        this.putTableData = [];
        this.fileNames = '';
    }

    // 删除明细
    private deleteDetail(): void {
        if (this.hasSelectedData.length < 1) {
            this.yh_message_warn('未选择删除项!');
        } else {
            this.delPendingData = this.hasSelectedData;
            this.deleteDialog = this.deleteDialog.getDeleteDialog('确认删除公司池下发行人？');
        }
    }

    private putDictfile(): void {
        (this.$refs['putInput'] as any).value = null;
        (this.$refs['putInput'] as any).click();
    }

    // 选取文件
    private putDictfiles(e) {
        let files = e.currentTarget.files;
        new Promise((resolve, reject) => {
            let reader = new FileReader();
            if (!files || files.length === 0) {
                // eslint-disable-next-line prefer-promise-reject-errors
                reject();
            }
            reader.readAsBinaryString(files[0]);

            reader.onload = e => {
                let webBook = XLSX.read(e.target.result, { type: 'binary' });
                let data = [];
                for (let sheet in webBook.Sheets) {
                    if (webBook.Sheets.hasOwnProperty(sheet)) {
                        data = data.concat(XLSX.utils.sheet_to_json(webBook.Sheets[sheet]));
                        break;
                    }
                }
                resolve(data);
            };
            reader.onerror = error => {
                reject(error);
            };
        }).then((res: any) => {
            try {
                let entryDetails = [];
                entryDetails = res
                    .map(item => {
                        return {
                            issueCode: Object.values(item)[0],
                            issueName: Object.values(item)[1],
                            issueNameSt: Object.values(item)[2],
                            key: Object.values(item)[0],
                        };
                    })
                    .filter(item => !!item.issueCode);
                if (entryDetails.length === 0) {
                    this.yh_message_error('数据格式不正确或者数据为空，导入失败');
                    return;
                }
                let putTableDataList = entryDetails;

                this.$axios({ method: 'post', url: `/componyPool/issueGroup/import/check/${this.currentData.id}`, data: putTableDataList }).then(
                    (res: any) => {
                        this.putTableDataList = res;
                        this.loadPageChange(1);
                    }
                );
                this.fileNames = files[0].name;
            } catch (e) {
                this.yh_message_error('数据格式不正确，导入失败');
            }
        });
    }
    private loadinDetailDialogClosed(): void {
        this.loadinDetailDialog.visible = false;
    }

    private loadinDetailDialogConfirm(): void {
        let entryDetails = this.putTableDataList;
        if (!entryDetails || entryDetails.length === 0) {
            this.yh_message_warn('请选择需要上传的条目文件');
            return;
        }
        this.$axios
            .post(
                '/componyPool/issueGroup/import/isGroup/issue/' + this.currentData.id,
                this.putTableDataList.map(item => item.issueCode)
            )
            .then((res: any) => {
                this.yh_message_success('导入成功');
                this.getDetailInfo(this.currentData.id);
                this.loadinDetailDialogClosed();
            });
    }
    async asycHandleClose(done) {
        let newVar = await this.editDetailDialogConfirm(false);
        await done();
    }

    private handleClose(done) {
        this.asycHandleClose(done);
    }
    handleSort(column): void {
        this.groupPage.currentPage = 1;
        if (column.order == 'ascending') {
            if (this.inputValueRight) {
                this.tableDataSearched.sort(this.dateData(column.prop, true));
                this.tableData = getCurrentPageData(this.tableDataSearched, this.groupPage.currentPage, this.groupPage.pageSize);
            } else {
                this.tableDataList.sort(this.dateData(column.prop, true));
                this.tableData = getCurrentPageData(this.tableDataList, this.groupPage.currentPage, this.groupPage.pageSize);
            }
        } else {
            if (this.inputValueRight) {
                this.tableDataSearched.sort(this.dateData(column.prop, true)).reverse();
                this.tableData = getCurrentPageData(this.tableDataSearched, this.groupPage.currentPage, this.groupPage.pageSize);
            } else {
                this.tableDataList.sort(this.dateData(column.prop, true)).reverse();
                this.tableData = getCurrentPageData(this.tableDataList, this.groupPage.currentPage, this.groupPage.pageSize);
            }
        }
    }
    dateData(property, bol) {
        return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            if (bol) {
                // 升序
                return Date.parse(value1) - Date.parse(value2);
            } else {
                // 降序
                return Date.parse(value2) - Date.parse(value1);
            }
        };
    }

    /**
     * 导出失败明细
     */
    downLoadFail(): void {
        downLoadFile({
            url: '/componyPool/issueGroup/import/download',
            method: 'post',
            data: this.putTableDataList,
        });
    }
}
</script>
<style lang="scss" scoped>
.pool-list {
    position: relative;
    height: 100%;
    .dict-r-slot {
        margin-left: 10px;
    }

    & /deep/ .el-dialog .el-dialog__body {
        max-height: 100vh;
    }
}
/deep/ .editDialog .el-dialog {
    margin-top: 10vh !important;
    .el-dialog__body {
        max-height: 90vh;
        padding: 10px;
    }
}
/deep/ .el-dialog .el-dialog__body {
    max-height: 100vh !important;
}
.el-icon-full-screen,
.el-icon-crop {
    position: absolute;
    top: 13px;
    right: 45px;
    color: white;
    &:hover {
        color: #909399;
    }
}
</style>
